package com.wzd.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzd.baseservice.exceptionHandler.BaseException;
import com.wzd.eduservice.client.OrderClient;
import com.wzd.eduservice.entity.EduCourse;
import com.wzd.eduservice.entity.EduTeacher;
import com.wzd.eduservice.entity.Live;
import com.wzd.eduservice.entity.frontvo.CourseQueryVo;
import com.wzd.eduservice.mapper.EduCourseMapper;
import com.wzd.eduservice.mapper.LiveMapper;
import com.wzd.eduservice.service.EduTeacherService;
import com.wzd.eduservice.service.LiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzd.eduservice.utils.SnowFlakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzd
 * @since 2021-04-25
 */
@Service
public class LiveServiceImpl extends ServiceImpl<LiveMapper, Live> implements LiveService {
    @Autowired
    private EduTeacherService teacherService;

    @Autowired
    private EduCourseServiceImpl courseService;

    @Autowired
    private EduCourseMapper courseMapper;

    @Autowired
    private OrderClient orderClient;

    @Value("${live.base.ip}")
    private String ip;

    @Value("${live.base.location}")
    private String location;

    public boolean save(Live live) {
        //校验
        EduCourse byId = courseService.getById(live.getCourceId());
        if (byId == null) {
            throw new BaseException(20001, "不存在id：【" + live.getTeacherId() + "】的课程");
        }
        EduTeacher byId1 = teacherService.getById(byId.getTeacherId());
        if (byId1 == null) {
            throw new BaseException(20001, "不存在id：【" + live.getTeacherId() + "】的老师");
        }
        // 一个课程只能有一个直播地址
        QueryWrapper<Live> liveQueryWrapper = new QueryWrapper<>();
        liveQueryWrapper.eq("cource_id", live.getCourceId());
        List<Live> lives = baseMapper.selectList(liveQueryWrapper);
        if (!CollectionUtils.isEmpty(lives)) {
            throw new BaseException(20001, "课程【" + byId.getTitle() + "】已经建立直播地址");
        }
        live.setTeacherId(byId.getTeacherId());
        // 生成房间号
        long l = SnowFlakeIdWorker.getInstance(1, 1, 1).nextId();
        String room = Long.toString(l);
        live.setRoom(room);
        // 生成链接
        String rmtp = "rtmp://" + ip + "/" + location + "/" + room;
        live.setRmtp(rmtp);
        live.setOnline(true);
        live.setIsPublic(false);
        int insert = baseMapper.insert(live);
        if (insert > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean startOnLine(String id) {
        Live live = baseMapper.selectById(id);
        // 每一个用户只用有一个课程正在直播
        QueryWrapper<Live> liveQueryWrapper = new QueryWrapper<>();
        liveQueryWrapper.eq("teacher_id", live.getTeacherId());
        List<Live> lives = baseMapper.selectList(liveQueryWrapper);
        Boolean online = live.getOnline();
        if (!online) {
            // 如果直播关闭，则判断是否有开启的直播，如果有开启的直播，则抛出异常
            for (Live life : lives) {
                if (life.getOnline()) {
                    throw new BaseException(20001, "只能开启一个直播");
                }
            }
        }
        live.setOnline(!online);
        return this.updateById(live);
    }

    @Override
    public boolean updataPublic(String id) {
        Live live = baseMapper.selectById(id);
        live.setIsPublic(!live.getIsPublic());
        return this.updateById(live);
    }

    @Override
    public Map<String, Object> liveFrontPageList(Page<EduCourse> pageParam, CourseQueryVo courseQuery, String memberIdByJwtToken) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        // 一级分类
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }
        // 二级分类
        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        // 开始对记录进行过滤
        QueryWrapper<Live> liveQueryWrapper = new QueryWrapper<>();
        liveQueryWrapper.eq("online", true);
        List<Live> lives = baseMapper.selectList(liveQueryWrapper);
        // 公开课
        // 用户购买的课程
        ArrayList<String> courseIds = new ArrayList<>();
        for (Live life : lives) {
            if (life.getIsPublic()) {
                courseIds.add(life.getCourceId());
            } else if (orderClient.isBuyCourse(memberIdByJwtToken, life.getCourceId())) {
                courseIds.add(life.getCourceId());
            }
        }

        queryWrapper.in("id", courseIds);

        courseMapper.selectPage(pageParam, queryWrapper);
        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public boolean isPublicByCourseId(String courseId) {
        QueryWrapper<Live> liveQueryWrapper = new QueryWrapper<>();
        liveQueryWrapper.eq("cource_id", courseId);
        Live live = baseMapper.selectOne(liveQueryWrapper);
        if (live != null) {
            return live.getIsPublic();
        } else {
            return false;
        }
    }

    public long getPages(List list, Long size) {
        if (size == 0L) {
            return 0L;
        } else {
            long pages = list.size() / size;
            if (list.size() % size != 0L) {
                ++pages;
            }
            return pages;
        }
    }

}
